package io.renren.sf.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.sf.dao.FrontUserListDao;
import io.renren.sf.dao.TeacherDao;
import io.renren.sf.entity.CbBookEntity;
import io.renren.sf.entity.TeacherEntity;
import io.renren.sf.service.TeacherService;
import io.renren.sf.vo.ProvinceVo;
import io.renren.sf.vo.TeacherVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import io.renren.sf.entity.CityEntity;
import io.renren.sf.service.CityService;
import io.renren.common.utils.R;



/**
 * 
 *
 * @author cyl_txw
 * @email cyl_txw@gmail.com
 * @date 2021-04-22 21:28:47
 */
@RestController
@RequestMapping("sf/city")
public class CityController {
    @Autowired
    private CityService cityService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private FrontUserListDao frontUserListDao;

    /**
     * 获取省市区下拉菜单
     */
    @GetMapping("/getCityList")
    public R getCityList(){
        return R.ok().put("cityList", cityService.getSsqAll());
    }
    /**
     * 获取省市区下拉菜单通过userId
     */
    @GetMapping("/getCityListByUserId/{userId}")
    public R getCityListByUserId(@PathVariable("userId") Long userId){
        if(userId == 1){
            // 超级管理员
            return R.ok().put("cityList", cityService.list()).put("cid", 110000); // 110000北京市
        }
        SysUserEntity byId = sysUserService.getById(userId);
        Integer cid = byId.getCid(); // 获取省市区id
        String cidStr = String.valueOf(cid);
        List<CityEntity> list = new ArrayList<>();
        // 判断是否是省或者直辖市
        if(cidStr.endsWith("0000")){
            // 是省
            list = cityService.list(new QueryWrapper<CityEntity>().eq("parentid", cid));
            if(!CollectionUtils.isEmpty(list)){
                List<CityEntity> help = new ArrayList<>(list); // 一定要另起炉灶
                for (CityEntity cityEntity : help) {
                    list.addAll(cityService.list(new QueryWrapper<CityEntity>().eq("parentid", cityEntity.getId())));
                }
            }
            // 加上本省
            list.add(cityService.getById(cid));

        }else if(cidStr.endsWith("00")){
            // 是市
            list = cityService.list(new QueryWrapper<CityEntity>().eq("parentid", cid).or().eq("id", cid));
        }else {
            // 县/区
            list = cityService.list(new QueryWrapper<CityEntity>().eq("id", cid));
        }
        return R.ok().put("cityList", list).put("cid", cid);
    }

    @GetMapping("/getCityListByUserId2/{userId}")
    public R getCityListByUserId2(@PathVariable("userId") Long userId){
        if(userId == 1){
            // 超级管理员
            return R.ok().put("cityList", cityService.getSsqAll()).put("cid", Arrays.asList(110000)); // 110000北京市
        }
        SysUserEntity byId = sysUserService.getById(userId);
        Integer cid = byId.getCid(); // 获取省市区id
        String cidStr = String.valueOf(cid);
        List list = null;
        LinkedList<Integer> cids = new LinkedList<>();
        // 判断是否是省或者直辖市
        if(cidStr.endsWith("0000")){
            // 是省
            list = cityService.getSsq(cid);
            cids.addLast(cid);
        }else if(cidStr.endsWith("00")){
            // 是市
            list = cityService.getSq(cid);
//            cids.addLast(Integer.parseInt(cidStr.substring(0, 2) + "0000"));
            cids.addLast(cid);
        }else {
            // 县/区
            list = cityService.getQ(cid);
//            cids.addLast(Integer.parseInt(cidStr.substring(0, 2) + "0000"));
//            cids.addLast(Integer.parseInt(cidStr.substring(0, 4) + "00"));
            cids.addLast(cid);
        }

        return R.ok().put("cityList", list).put("cid", cids);
    }

    @GetMapping("/getCityListByUserId3/{userId}")
    public R getCityListByUserId3(@PathVariable("userId") Long userId){
        SysUserEntity byId = sysUserService.getById(userId);
        Integer cid = byId.getCid(); // 获取省市区id
        String cidStr = String.valueOf(cid);
        LinkedList<Integer> cids = new LinkedList<>();
        // 判断是否是省或者直辖市
        if(cidStr.endsWith("0000")){
            // 是省
            cids.addLast(cid);
        }else if(cidStr.endsWith("00")){
            // 是市
            cids.addLast(Integer.parseInt(cidStr.substring(0, 2) + "0000"));
            cids.addLast(cid);
        }else {
            // 县/区
            cids.addLast(Integer.parseInt(cidStr.substring(0, 2) + "0000"));
            cids.addLast(Integer.parseInt(cidStr.substring(0, 4) + "00"));
            cids.addLast(cid);
        }

        return R.ok().put("cid", cids);
    }


    /**
     * 获取前台用户通过cid
     */
    @GetMapping("/getUserListByCid")
    public R getUserListByCid(@RequestParam Map<String, Object> params) throws ParseException {
        String cid = (String) params.get("cid"); // todo 判断Null
        long page = Long.parseLong((String) params.get("page"));
        long limit = Long.parseLong((String) params.get("limit"));
        QueryWrapper<TeacherVo> queryWrapper = new QueryWrapper<>();
        if (params.get("startdate") != null && params.get("stopdate") != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startdate = simpleDateFormat.parse((String) params.get("startdate"));
            Date stopdate = simpleDateFormat.parse((String) params.get("stopdate"));
            queryWrapper.between("createtime", startdate, stopdate);
        }

        Page<TeacherVo> userPage = new Page<TeacherVo>(page, limit);
        List<CityEntity> list = new ArrayList<>();
        List<Integer> cidList = new ArrayList<>(); // 所有区/县id
        // 判断是否是省或者直辖市
        if(cid.endsWith("0000")){
            // 是省
            list = cityService.list(new QueryWrapper<CityEntity>().eq("parentid", Integer.parseInt(cid)));
            if(!CollectionUtils.isEmpty(list)){
                List<CityEntity> help = new ArrayList<>(list); // 一定要另起炉灶
                for (CityEntity cityEntity : help) {
                    list.addAll(cityService.list(new QueryWrapper<CityEntity>().eq("parentid", cityEntity.getId())));
                }
            }
            cidList = list.stream().filter(f -> {
                return !f.getParentid().equals(Integer.parseInt(cid));
            }).map(CityEntity::getId).collect(Collectors.toList());
        }else if(cid.endsWith("00")){
            // 是市
            list = cityService.list(new QueryWrapper<CityEntity>().eq("parentid", Integer.parseInt(cid)));
            cidList = list.stream() .map(CityEntity::getId).collect(Collectors.toList());
        }else {
            // 县/区
            cidList.add(Integer.parseInt(cid));
        }
        if(!CollectionUtils.isEmpty(cidList)){
            queryWrapper.in("sc.cid", cidList);
        }
        frontUserListDao.selectFrontUserEntityPageOnTj(userPage, queryWrapper); // todo user_type = 2
        return R.ok().put("userPage", userPage);
    }
    /**
     * 获取省市区账号开通数量
     */
    @GetMapping("/getUserNum/{cid}")
    public R getUserNum(@PathVariable("cid")Long cid){
        String cidStr = String.valueOf(cid);
        List<Map<String, Object>> list = new ArrayList<>();
        // 判断是否是省或者直辖市
        if(cidStr.endsWith("0000")){
            // 是省
            list = cityService.getUserNumByProvinceId(cid);
        }else if(cidStr.endsWith("00")){
            // 是市
            list = cityService.getUserNumByCityId(cid);
        }else {
            // 县/区
            list = cityService.getUserNumByRegionId(cid);
        }
        return R.ok().put("pieData", list);
    }
    /**
     * 获取省市区账号登录次数
     */
    @GetMapping("/getUserLoginNum/{cid}")
    public R getUserLoginNum(@PathVariable("cid")Long cid){
        String cidStr = String.valueOf(cid);
        List<Map<String, Object>> list = new ArrayList<>();
        // 判断是否是省或者直辖市
        if(cidStr.endsWith("0000")){
            // 是省
            list = cityService.getUserLoginNumByProvinceId(cid);
        }else if(cidStr.endsWith("00")){
            // 是市
            list = cityService.getUserLoginNumByCityId(cid);
        }else {
            // 县/区
            list = cityService.getUserLoginNumByRegionId(cid);
        }
        return R.ok().put("pieData2", list);
    }
    /**
     * 获取省市区账号登录时间
     */
    @GetMapping("/getUserLoginTime/{cid}")
    public R getUserLoginTime(@PathVariable("cid")Long cid){
        String cidStr = String.valueOf(cid);
        List<Map<String, Object>> list = new ArrayList<>();
        // 判断是否是省或者直辖市
        if(cidStr.endsWith("0000")){
            // 是省
            list = cityService.getUserLoginTimeByProvinceId(cid);
        }else if(cidStr.endsWith("00")){
            // 是市
            list = cityService.getUserLoginTimeByCityId(cid);
        }else {
            // 县/区
            list = cityService.getUserLoginTimeByRegionId(cid);
        }
        return R.ok().put("barData", list);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    //@RequiresPermissions("sf:city:info")
    public R info(@PathVariable("id") Integer id){
		CityEntity city = cityService.getById(id);

        return R.ok().put("city", city);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    //@RequiresPermissions("sf:city:save")
    public R save(@RequestBody CityEntity city){
		cityService.save(city);

        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    //@RequiresPermissions("sf:city:update")
    public R update(@RequestBody CityEntity city){
		cityService.updateById(city);

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    //@RequiresPermissions("sf:city:delete")
    public R delete(@RequestBody Integer[] ids){
		cityService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
